<template>
  <el-dialog
    :model-value="modelValue"
    @update:model-value="$emit('update:modelValue', $event)"
    title="工单详情"
    width="800px"
    :close-on-click-modal="false"
  >
    <div class="ticket-detail" v-if="ticket">
      <!-- 工单基本信息 -->
      <div class="ticket-header">
        <div class="header-left">
          <h2 class="ticket-title">
            #{{ ticket.id }} {{ ticket.title }}
            <el-tag v-if="ticket.isUrgent" type="danger" size="small" class="urgent-tag">
              紧急
            </el-tag>
          </h2>
          <div class="ticket-meta">
            <span class="meta-item">
              <el-icon><User /></el-icon>
              创建者：系统管理员
            </span>
            <span class="meta-item">
              <el-icon><Clock /></el-icon>
              创建时间：{{ formatDateTime(ticket.createdAt) }}
            </span>
          </div>
        </div>
        <div class="header-right">
          <el-tag :type="getPriorityType(ticket.priority)" size="large">
            {{ getPriorityText(ticket.priority) }}优先级
          </el-tag>
        </div>
      </div>

      <!-- 主要内容区域 -->
      <div class="ticket-content">
        <!-- 左侧：工单内容和操作记录 -->
        <div class="content-left">
          <!-- 工单描述 -->
          <div class="content-section">
            <h3 class="section-title">工单描述</h3>
            <div class="ticket-description">
              {{ ticket.description }}
            </div>
          </div>

          <!-- 操作记录/评论区 -->
          <div class="content-section">
            <h3 class="section-title">
              操作记录
              <el-button type="primary" size="small" @click="showAddComment = !showAddComment">
                添加评论
              </el-button>
            </h3>
            
            <!-- 添加评论框 -->
            <div v-if="showAddComment" class="add-comment">
              <el-input
                v-model="newComment"
                type="textarea"
                :rows="3"
                placeholder="请输入评论内容..."
                maxlength="200"
                show-word-limit
              />
              <div class="comment-actions">
                <el-button size="small" @click="cancelComment">取消</el-button>
                <el-button type="primary" size="small" @click="addComment" :loading="addingComment">
                  发表评论
                </el-button>
              </div>
            </div>
            
            <!-- 操作记录时间轴 -->
            <div class="timeline">
              <div 
                v-for="(record, index) in operationRecords" 
                :key="index"
                class="timeline-item"
              >
                <div class="timeline-marker" :class="record.type">
                  <el-icon>
                    <component :is="getTimelineIcon(record.type)" />
                  </el-icon>
                </div>
                <div class="timeline-content">
                  <div class="timeline-header">
                    <span class="timeline-user">{{ record.user }}</span>
                    <span class="timeline-action">{{ record.action }}</span>
                    <span class="timeline-time">{{ formatDateTime(record.time) }}</span>
                  </div>
                  <div class="timeline-detail" v-if="record.detail">
                    {{ record.detail }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧：操作面板和SLA信息 -->
        <div class="content-right">
          <!-- 操作面板 -->
          <div class="operation-panel">
            <h3 class="panel-title">操作面板</h3>
            
            <!-- 分配用户 -->
            <div class="operation-item">
              <label class="operation-label">分配给：</label>
              <el-select 
                v-model="currentAssigneeId" 
                placeholder="选择用户" 
                style="width: 100%;"
                @change="handleAssigneeChange"
              >
                <el-option label="未分配" :value="null" />
                <el-option
                  v-for="user in userList"
                  :key="user.id"
                  :label="user.name"
                  :value="user.id"
                />
              </el-select>
            </div>
            
            <!-- 更改状态 -->
            <div class="operation-item">
              <label class="operation-label">状态：</label>
              <el-select 
                v-model="currentStatus" 
                style="width: 100%;"
                @change="handleStatusChange"
              >
                <el-option label="待处理" value="pending" />
                <el-option label="进行中" value="in-progress" />
                <el-option label="已完成" value="completed" />
                <el-option label="已归档" value="archived" />
              </el-select>
            </div>
            
            <!-- 操作按钮 -->
            <div class="operation-buttons">
              <el-button type="warning" :icon="Edit" @click="editTicket" block>
                编辑工单
              </el-button>
              <el-button type="info" :icon="FolderOpened" @click="archiveTicket" block>
                归档工单
              </el-button>
              <el-button type="danger" :icon="Delete" @click="deleteTicket" block>
                删除工单
              </el-button>
            </div>
          </div>

          <!-- SLA信息 -->
          <div class="sla-panel">
            <h3 class="panel-title">SLA信息</h3>
            <div class="sla-content">
              <div class="sla-item">
                <label class="sla-label">截止时间：</label>
                <span class="sla-value">{{ formatDateTime(ticket.slaDeadline) }}</span>
              </div>
              <div class="sla-item">
                <label class="sla-label">剩余时间：</label>
                <span class="sla-value" :class="getSLATextClass(ticket)">
                  {{ getSLAText(ticket) }}
                </span>
              </div>
              <div class="sla-progress">
                <el-progress 
                  :percentage="getSLAPercentage(ticket)" 
                  :color="getSLAColor(ticket)"
                  :stroke-width="8"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="$emit('update:modelValue', false)">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  User, 
  Clock, 
  Edit, 
  FolderOpened, 
  Delete,
  ChatDotRound,
  Operation,
  Check,
  Warning
} from '@element-plus/icons-vue'

// Props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  ticket: {
    type: Object,
    default: null
  },
  userList: {
    type: Array,
    default: () => []
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'update'])

console.log('工单详情对话框组件加载')

// 响应式数据
const showAddComment = ref(false)
const newComment = ref('')
const addingComment = ref(false)
const currentAssigneeId = ref(null)
const currentStatus = ref('')

// 操作记录数据
const operationRecords = ref([
  {
    type: 'create',
    user: '系统管理员',
    action: '创建了工单',
    time: '2025-01-15 09:30:00',
    detail: '工单已创建，等待分配处理人员'
  },
  {
    type: 'assign',
    user: '项目经理',
    action: '分配给张三',
    time: '2025-01-15 09:35:00',
    detail: '已将工单分配给技术支持团队的张三处理'
  },
  {
    type: 'comment',
    user: '张三',
    action: '添加了评论',
    time: '2025-01-15 10:00:00',
    detail: '已开始调查问题，初步判断是服务器负载过高导致'
  },
  {
    type: 'status',
    user: '张三',
    action: '更改状态为进行中',
    time: '2025-01-15 10:05:00',
    detail: '开始处理工单，预计2小时内解决'
  }
])

// 监听工单数据变化
watch(() => props.ticket, (newVal) => {
  if (newVal) {
    currentAssigneeId.value = newVal.assignee?.id || null
    currentStatus.value = newVal.status || 'pending'
  }
}, { immediate: true })

// 取消评论
const cancelComment = () => {
  showAddComment.value = false
  newComment.value = ''
}

// 添加评论
const addComment = async () => {
  if (!newComment.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }
  
  addingComment.value = true
  
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 添加到操作记录
    operationRecords.value.unshift({
      type: 'comment',
      user: '当前用户',
      action: '添加了评论',
      time: new Date().toISOString(),
      detail: newComment.value
    })
    
    ElMessage.success('评论添加成功')
    cancelComment()
    
  } catch (error) {
    console.error('添加评论失败:', error)
    ElMessage.error('添加评论失败，请重试')
  } finally {
    addingComment.value = false
  }
}

// 处理分配用户变更
const handleAssigneeChange = async (userId) => {
  console.log('分配用户变更:', userId)
  
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 300))
    
    const user = userId ? props.userList.find(u => u.id === userId) : null
    const actionText = user ? `分配给${user.name}` : '取消分配'
    
    // 添加操作记录
    operationRecords.value.unshift({
      type: 'assign',
      user: '当前用户',
      action: actionText,
      time: new Date().toISOString(),
      detail: user ? `工单已分配给${user.name}处理` : '工单分配已取消'
    })
    
    // 更新工单数据
    const updatedTicket = {
      ...props.ticket,
      assignee: user
    }
    
    emit('update', updatedTicket)
    ElMessage.success('分配更新成功')
    
  } catch (error) {
    console.error('分配用户失败:', error)
    ElMessage.error('分配失败，请重试')
    // 恢复原值
    currentAssigneeId.value = props.ticket?.assignee?.id || null
  }
}

// 处理状态变更
const handleStatusChange = async (status) => {
  console.log('状态变更:', status)
  
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 300))
    
    const statusTexts = {
      pending: '待处理',
      'in-progress': '进行中',
      completed: '已完成',
      archived: '已归档'
    }
    
    // 添加操作记录
    operationRecords.value.unshift({
      type: 'status',
      user: '当前用户',
      action: `更改状态为${statusTexts[status]}`,
      time: new Date().toISOString(),
      detail: `工单状态已更新为${statusTexts[status]}`
    })
    
    // 更新工单数据
    const updatedTicket = {
      ...props.ticket,
      status: status
    }
    
    emit('update', updatedTicket)
    ElMessage.success('状态更新成功')
    
  } catch (error) {
    console.error('状态更新失败:', error)
    ElMessage.error('状态更新失败，请重试')
    // 恢复原值
    currentStatus.value = props.ticket?.status || 'pending'
  }
}

// 编辑工单
const editTicket = () => {
  console.log('编辑工单')
  ElMessage.info('编辑功能开发中')
}

// 归档工单
const archiveTicket = async () => {
  console.log('归档工单')
  
  try {
    const confirmed = await ElMessageBox.confirm(
      '确定要归档此工单吗？归档后工单将不再显示在活跃列表中。',
      '归档确认',
      {
        confirmButtonText: '确定归档',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    if (confirmed) {
      await handleStatusChange('archived')
      ElMessage.success('工单已归档')
    }
  } catch (error) {
    console.log('用户取消归档')
  }
}

// 删除工单
const deleteTicket = async () => {
  console.log('删除工单')
  
  try {
    const confirmed = await ElMessageBox.confirm(
      `确定要删除工单 #${props.ticket?.id} 吗？此操作不可恢复。`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'error'
      }
    )
    
    if (confirmed) {
      ElMessage.success('工单删除成功')
      emit('update:modelValue', false)
    }
  } catch (error) {
    console.log('用户取消删除')
  }
}

// 获取时间轴图标
const getTimelineIcon = (type) => {
  const icons = {
    create: 'Plus',
    assign: 'User',
    comment: 'ChatDotRound',
    status: 'Operation'
  }
  return icons[type] || 'Operation'
}

// 工具函数
const getPriorityType = (priority) => {
  const types = {
    high: 'danger',
    medium: 'warning',
    low: 'info'
  }
  return types[priority] || 'info'
}

const getPriorityText = (priority) => {
  const texts = {
    high: '高',
    medium: '中',
    low: '低'
  }
  return texts[priority] || '未知'
}

const formatDateTime = (dateTime) => {
  return new Date(dateTime).toLocaleString('zh-CN')
}

const getSLAPercentage = (ticket) => {
  const now = new Date()
  const created = new Date(ticket.createdAt)
  const deadline = new Date(ticket.slaDeadline)
  
  const totalTime = deadline.getTime() - created.getTime()
  const usedTime = now.getTime() - created.getTime()
  
  return Math.min(Math.max((usedTime / totalTime) * 100, 0), 100)
}

const getSLAColor = (ticket) => {
  const percentage = getSLAPercentage(ticket)
  if (percentage >= 90) return '#f56c6c'
  if (percentage >= 70) return '#e6a23c'
  return '#67c23a'
}

const getSLAText = (ticket) => {
  const now = new Date()
  const deadline = new Date(ticket.slaDeadline)
  const diff = deadline.getTime() - now.getTime()
  
  if (diff <= 0) return '已超时'
  
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
  
  if (hours > 0) return `${hours}h ${minutes}m`
  return `${minutes}m`
}

const getSLATextClass = (ticket) => {
  const percentage = getSLAPercentage(ticket)
  if (percentage >= 90) return 'sla-danger'
  if (percentage >= 70) return 'sla-warning'
  return 'sla-normal'
}
</script>

<style scoped>
.ticket-detail {
  max-height: 70vh;
  overflow-y: auto;
}

/* 工单头部 */
.ticket-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding-bottom: 20px;
  border-bottom: 1px solid #e5e7eb;
  margin-bottom: 24px;
}

.header-left {
  flex: 1;
}

.ticket-title {
  font-size: 20px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 12px 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.urgent-tag {
  flex-shrink: 0;
}

.ticket-meta {
  display: flex;
  gap: 24px;
  color: #6b7280;
  font-size: 14px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 6px;
}

.header-right {
  flex-shrink: 0;
}

/* 主要内容区域 */
.ticket-content {
  display: flex;
  gap: 24px;
}

.content-left {
  flex: 2;
}

.content-right {
  flex: 1;
  min-width: 280px;
}

/* 内容区块 */
.content-section {
  margin-bottom: 32px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #374151;
  margin: 0 0 16px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.ticket-description {
  background: #f9fafb;
  padding: 16px;
  border-radius: 8px;
  border: 1px solid #e5e7eb;
  line-height: 1.6;
  color: #374151;
}

/* 添加评论 */
.add-comment {
  margin-bottom: 20px;
  padding: 16px;
  background: #f9fafb;
  border-radius: 8px;
  border: 1px solid #e5e7eb;
}

.comment-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 12px;
}

/* 时间轴 */
.timeline {
  position: relative;
}

.timeline-item {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
  position: relative;
}

.timeline-item:not(:last-child)::after {
  content: '';
  position: absolute;
  left: 15px;
  top: 32px;
  bottom: -20px;
  width: 2px;
  background: #e5e7eb;
}

.timeline-marker {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 14px;
  flex-shrink: 0;
}

.timeline-marker.create {
  background: #10b981;
}

.timeline-marker.assign {
  background: #3b82f6;
}

.timeline-marker.comment {
  background: #8b5cf6;
}

.timeline-marker.status {
  background: #f59e0b;
}

.timeline-content {
  flex: 1;
  padding-top: 4px;
}

.timeline-header {
  display: flex;
  gap: 8px;
  align-items: center;
  margin-bottom: 4px;
}

.timeline-user {
  font-weight: 500;
  color: #374151;
}

.timeline-action {
  color: #6b7280;
}

.timeline-time {
  color: #9ca3af;
  font-size: 12px;
  margin-left: auto;
}

.timeline-detail {
  color: #6b7280;
  font-size: 14px;
  line-height: 1.5;
}

/* 操作面板 */
.operation-panel,
.sla-panel {
  background: #f9fafb;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.panel-title {
  font-size: 16px;
  font-weight: 600;
  color: #374151;
  margin: 0 0 16px 0;
}

.operation-item {
  margin-bottom: 16px;
}

.operation-label {
  display: block;
  font-size: 14px;
  font-weight: 500;
  color: #374151;
  margin-bottom: 8px;
}

.operation-buttons {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

/* SLA面板 */
.sla-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.sla-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.sla-label {
  font-size: 14px;
  color: #6b7280;
}

.sla-value {
  font-size: 14px;
  font-weight: 500;
}

.sla-normal {
  color: #16a34a;
}

.sla-warning {
  color: #d97706;
}

.sla-danger {
  color: #dc2626;
}

.sla-progress {
  margin-top: 8px;
}

/* 对话框底部 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .ticket-content {
    flex-direction: column;
  }
  
  .content-right {
    min-width: auto;
  }
  
  .ticket-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .ticket-meta {
    flex-direction: column;
    gap: 8px;
  }
}
</style>
